window.interaction = {
    //存放加入的组信息
    _groupInfos: new Array(),
    //用户状态回调接口
    _stateCallback: {},
    //接收消息回调接口
    _receiveCallback: {},
    //状态对象
    stateObj: {
        getConnectSucState: function () {
            return {statuscode: 10001, msg: "信道连接成功"};
        },
        getConnectFailState: function () {
            return {statuscode: 10002, msg: "信道连接失败"};
        },
        getConnectSlowState: function () {
            return {statuscode: 10003, msg: "信道网络不好"};
        },
        getDisconnectState: function () {
            return {statuscode: 10004, msg: "信道连接断开"};
        },
        getReconnectState: function () {
            return {statuscode: 10005, msg: "信道重连断开"};
        },
        getSendMsgErrState: function () {
            return {statuscode: 10006, msg: "发送消息失败"};
        },
        getJoinRoomSucState: function () {
            return {statuscode: 10007, msg: "加入组成功"};
        },
        getJoinRoomFailState: function () {
            return {statuscode: 10008, msg: "加入组失败"};
        },
        getLeaveRoomSucState: function () {
            return {statuscode: 10009, msg: "退出组成功"};
        },
        getLeaveRoomFailState: function () {
            return {statuscode: 10010, msg: "退出组失败"};
        }
    },
    _jsonToString: function (groupcontext) {
        return JSON.stringify(groupcontext);
    },
    _delGroup: function (groupcontext) {
        var strJson = this._jsonToString(groupcontext);

        for (var i = 0; i < this._groupInfos.length; i++) {
            if (this._groupInfos[i] == strJson) {
                var del = this._groupInfos.splice(i, 1);
                console.log("删除组:" + del);
                return;
            }
        }
        console.log("组:" + groupcontext + "不需要删除");
    },
    _addToGroup: function (groupcontext) {
        this._groupInfos.push(this._jsonToString(groupcontext));
    },
    _existGroup: function (groupcontext) {
        var strJson = this._jsonToString(groupcontext);
        var finded = false;
        for (var i = 0; i < this._groupInfos.length; i++) {
            if (this._groupInfos[i] == strJson) {
                finded = true;
                break;
            }
        }
        return finded;
    },
    _getClient: function () {
        return $.connection.chatHub;
    },
    _getConnect: function () {
        return $.connection.hub;
    },
    _onStartDone: function () {
    //通知客户端连接成功，并重新加入组
        this._stateCallback(window.interaction.stateObj.getConnectSucState());

        // for (var i = 0; i < this._groupInfos.length; i++) {
        //     this._join(JSON.parse(this._groupInfos[i]));
        // }
    },
    _join: function (groupcontext) {
        var client = this._getClient();
        var group = groupcontext;

        client.server.joinRoombyRoleType(
            group.businessType,
            group.activityId,
            group.roleType,
            group.programId)
            .done(function () {
                window.interaction._stateCallback(window.interaction.stateObj.getJoinRoomSucState());
                console.log("加入组:[" + window.interaction._jsonToString(groupcontext) + "]成功");
            }).fail(function (err) {
            window.interaction._stateCallback(window.interaction.stateObj.getJoinRoomFailState());
            console.log(err, "加入组:[" + window.interaction._jsonToString(groupcontext) + "]失败");
        });
    },
    _leave: function (groupcontext) {
        var client = this._getClient();
        var group = groupcontext;

        this._delGroup(groupcontext);

        client.server.leaveRoom(group.businessType,
            group.activityId, group.roleType, group.programId)
            .done(function () {
                console.log("退出组:[" + window.interaction._jsonToString(groupcontext) + "]成功");
                window.interaction._stateCallback(window.interaction.stateObj.getLeaveRoomSucState());
            }).fail(function (err) {
            window.interaction._stateCallback(window.interaction.stateObj.getLeaveRoomFailState());
            console.log(err, "退出组:[" + window.interaction._jsonToString(groupcontext) + "]失败");
        });
    },
    _receiveMsg: function (msg) {
        if (window.interaction._receiveCallback != null) {
            window.interaction._receiveCallback(msg);
        }
    },
    //将网络状态或执行状态回调给客户端
    _onStateCallback: function (stateobj) {
        if (this._stateCallback != null)
            this._stateCallback(stateobj);
    },
    //网络断开时通知客户端
    _siglarDisconnectEvent: function () {
        this._getConnect().disconnected(function () {
            console.log("与互动服务断开连接...");
            window.interaction._onStateCallback(window.interaction.stateObj.getDisconnectState());
        });
    },
    init: function (host,
                    isdebug,
                    receivecallback/*仅对非app客户端使用*/,
                    statecallback/*仅对非app客户端使用*/) {
        this._groupInfos = new Array();
        var url = window.location.protocol + "//" + host + "/signalr";
        this._getConnect().url = url;
        this._getConnect().logging = isdebug;

        //注册signalr断开事件
        this._siglarDisconnectEvent();

        //注册接收数据回调函数
        this._receiveCallback = receivecallback;
        //注册signalr状态回调函数
        this._stateCallback = statecallback;

        //注册数据的回调函数，状态回调函数
        this._getClient().client.broadcastMessage = this._receiveMsg;

        console.log("连接互动服务地址:" + url);
    },
    connect: function () {
        //每次启动链接时，尝试链接外部
        this._getConnect().start().done(function () {
            window.interaction._onStartDone();
        });
    },
    close: function () {
        alert("关闭开始");
        //关闭的时候，将加入的组全部释放掉
        this._getConnect().stop();
        this._groupInfos.length = 0;
        alert("关闭结束");
    },
    join: function (groupcontext) {
    // 如果已经加入组了，直接返回
    //     var finded = this._existGroup(groupcontext);
    //     if (finded)
    //         return;

        this._join(groupcontext);
    },
    leave: function (groupcontext) {
        this._leave(groupcontext);
    },
    sendinteractionmsg: function (msg) {
        var errState = window.interaction.stateObj.getSendMsgErrState();
        try {
            this._getClient().server.sendMsg(msg)
                .done(function () {
                    console.log("发送消息成功" + new Date());
                  //  alert("发送消息成功")
        })
                .fail(function (err) {
                //    alert("发送消息失败")
                    console.error(err, errState, new Date());
                    window.interaction._onStateCallback(errState);
                });
        } catch (err) {
            console.error(err, errState, new Date());
            window.interaction._onStateCallback(errState);
        }
    }
};